using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Text;

namespace SumerCoreDevOps.Infrastructure.Libraries;

/// <summary>
/// Maven 操作库
/// </summary>
public class MavenLibrary
{
    private readonly ILogger<MavenLibrary> _logger;

    public MavenLibrary(ILogger<MavenLibrary> logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// 部署到 Maven 仓库
    /// </summary>
    public async Task<bool> DeployToRepositoryAsync(
        string projectPath,
        string repositoryUrl,
        string repositoryId,
        string username,
        string password)
    {
        try
        {
            _logger.LogInformation("开始部署到 Maven 仓库: {Url}", repositoryUrl);

            // 创建临时 settings.xml
            var settingsXml = GenerateSettingsXml(repositoryId, username, password);
            var settingsPath = Path.Combine(Path.GetTempPath(), $"maven-settings-{Guid.NewGuid()}.xml");
            await File.WriteAllTextAsync(settingsPath, settingsXml);

            try
            {
                // 配置 Maven 命令
                var arguments = new StringBuilder();
                arguments.Append("deploy ");
                arguments.Append($"-DaltDeploymentRepository={repositoryId}::default::{repositoryUrl} ");
                arguments.Append($"-s \"{settingsPath}\" ");
                arguments.Append("-DskipTests");

                var result = await ExecuteMavenCommandAsync(projectPath, arguments.ToString());

                if (result.ExitCode == 0)
                {
                    _logger.LogInformation("Maven 部署成功");
                    return true;
                }
                else
                {
                    _logger.LogError("Maven 部署失败: {Output}", result.Output);
                    return false;
                }
            }
            finally
            {
                // 清理临时文件
                if (File.Exists(settingsPath))
                {
                    File.Delete(settingsPath);
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "部署到 Maven 仓库失败");
            return false;
        }
    }

    /// <summary>
    /// 执行 Maven 构建
    /// </summary>
    public async Task<(bool Success, string Output)> BuildAsync(
        string projectPath,
        string goals = "clean package",
        bool skipTests = false)
    {
        try
        {
            _logger.LogInformation("开始 Maven 构建: {Path}", projectPath);

            var arguments = goals;
            if (skipTests)
            {
                arguments += " -DskipTests";
            }

            var result = await ExecuteMavenCommandAsync(projectPath, arguments);

            if (result.ExitCode == 0)
            {
                _logger.LogInformation("Maven 构建成功");
                return (true, result.Output);
            }
            else
            {
                _logger.LogError("Maven 构建失败: {Output}", result.Output);
                return (false, result.Output);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Maven 构建异常");
            return (false, ex.Message);
        }
    }

    /// <summary>
    /// 执行 Maven 命令
    /// </summary>
    private async Task<(int ExitCode, string Output)> ExecuteMavenCommandAsync(
        string workingDirectory,
        string arguments)
    {
        var startInfo = new ProcessStartInfo
        {
            FileName = "mvn",
            Arguments = arguments,
            WorkingDirectory = workingDirectory,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        var output = new StringBuilder();

        using var process = new Process { StartInfo = startInfo };

        process.OutputDataReceived += (sender, e) =>
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                output.AppendLine(e.Data);
                _logger.LogDebug("Maven: {Line}", e.Data);
            }
        };

        process.ErrorDataReceived += (sender, e) =>
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                output.AppendLine(e.Data);
                _logger.LogWarning("Maven Error: {Line}", e.Data);
            }
        };

        process.Start();
        process.BeginOutputReadLine();
        process.BeginErrorReadLine();

        await process.WaitForExitAsync();

        return (process.ExitCode, output.ToString());
    }

    /// <summary>
    /// 生成 Maven settings.xml
    /// </summary>
    private string GenerateSettingsXml(string serverId, string username, string password)
    {
        return $@"<?xml version=""1.0"" encoding=""UTF-8""?>
<settings xmlns=""http://maven.apache.org/SETTINGS/1.0.0""
          xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
          xsi:schemaLocation=""http://maven.apache.org/SETTINGS/1.0.0
          http://maven.apache.org/xsd/settings-1.0.0.xsd"">
    <servers>
        <server>
            <id>{serverId}</id>
            <username>{username}</username>
            <password>{password}</password>
        </server>
    </servers>
</settings>";
    }
}
